package com.servlet.article;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.ArticleDAO;
import com.dao.UsersDAO;
import com.entity.Article;
import com.entity.Users;

public class AddArticleServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String userName = request.getParameter("user_name");
		String articleName = request.getParameter("article_name");
		String articleContent = request.getParameter("article_content");
        
		UsersDAO usersDAO = new UsersDAO();
		Users users = usersDAO.findByName(userName);
		int userId=users.getUser_id();
		Article article = new Article(userId, articleName, articleContent);
		article.setArticle_content(articleContent);
		ArticleDAO articlesDAO = new ArticleDAO();
		if (articlesDAO.save(article)) {
			request.getRequestDispatcher("/servlet/FindAllArticleServlet")
					.forward(request, response);
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String userName = request.getParameter("user_name");
		String articleName = request.getParameter("article_name");
		String articleContent = request.getParameter("article_content");
        
		UsersDAO usersDAO = new UsersDAO();
		Users users = usersDAO.findByName(userName);//通过已给的用户名 找到对应的用户id
		int userId=users.getUser_id();
		Article article = new Article(userId, articleName, articleContent);
		article.setArticle_content(articleContent);
		ArticleDAO articlesDAO = new ArticleDAO();
		if (articlesDAO.save(article)) {
			request.getRequestDispatcher("/servlet/FindAllArticleServlet")
					.forward(request, response);
			return;
		}
	}

}
